package com.pyue.eam.app.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.app.api.dto.AppUserInfo;
import com.pyue.eam.app.api.entity.AppSocialDetails;
import com.pyue.eam.app.api.entity.AppUser;
import com.pyue.eam.app.handler.IdentifyDto;
import com.pyue.eam.app.handler.LoginHandler;
import com.pyue.eam.app.mapper.AppSocialDetailsMapper;
import com.pyue.eam.app.mapper.AppUserMapper;
import com.pyue.eam.app.service.AppSocialDetailsService;
import com.pyue.eam.common.core.constant.CacheConstants;
import com.pyue.eam.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author eam
 * @date 2018年08月16日
 */
@Slf4j
@AllArgsConstructor
@Service("appSocialDetailsService")
public class AppSocialDetailsServiceImpl extends ServiceImpl<AppSocialDetailsMapper, AppSocialDetails>
        implements AppSocialDetailsService {

    private final Map<String, LoginHandler> loginHandlerMap;

    private final CacheManager cacheManager;

    private final AppUserMapper appUserMapper;

    /**
     * 绑定社交账号
     *
     * @param type type
     * @param code code
     * @return
     */
    @Override
    public Boolean bindSocial(String type, String code) {
        LoginHandler loginHandler = loginHandlerMap.get(type);
        // 绑定逻辑
        IdentifyDto identify = loginHandler.identify(code);
        AppUser user = appUserMapper.selectById(SecurityUtils.getUser().getId());
        loginHandler.bind(user, identify);

        // 更新緩存
        cacheManager.getCache(CacheConstants.USER_DETAILS_MINI).evict(user.getUsername());
        return Boolean.TRUE;
    }

    /**
     * 根据入参查询用户信息
     *
     * @param inStr TYPE@code
     * @return
     */
    @Override
    public AppUserInfo getUserInfo(String inStr) {
        String[] inStrs = inStr.split(StringPool.AT);
        String type = inStrs[0];
        String loginStr = inStr.substring(type.length() + 1);
        return loginHandlerMap.get(type).handle(loginStr);
    }

}
